/**
 * Copyright 2012 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License.  You may obtain a copy
 * of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */

$(document).ready(function() {

  if (config && config.embedded_url_prefix) {
    $("a[href]").each( function() {
      var n = $(this);
      var path = $(this).attr('href');
      if (path.match(/^(https?:\/\/|\/admin)/)) return;
      if (path[0] === '?') path = window.location.pathname + path;
      $(this).attr('href', config.embedded_url_prefix + path);
      $(this).attr('target', '_top');
    });
  }

    $(".voter").click(function() {
        var voter = $(this)
        var entry = voter.closest(".entry");
        var id = entry.attr("memeId");
        $.post("/vote/"+id, function(data){
            var arr = data.split(',', 2);
            entry.find(".voteCount").text(arr[0]);
            if (arr[1] == 'True'){
              voter.addClass('voted');
            } else {
              voter.removeClass('voted');
            }
          })
      }
    );

    $("#createCaption").click(function() {
        $('#createCaption').slideUp('fast');
        $('#creatememe').slideDown('fast');
      });

    var aligns = ['left', 'center', 'right'];
    var lines = ['top', 'middle', 'bottom'];

    for (var i = 0; i < lines.length; ++i) {
      for (var j = 0; j < aligns.length; ++j) {
        var button = $('#' + lines[i] + 'align' + aligns[j]);
        button.on(
            'click',
            function(line, pos, element) {
              return function() {
                $('#' + line + 'align').val(pos);
                element.parent().find(".selected").removeClass("selected");
                element.addClass("selected");
                Contest.previewImage.trigger();
              };
            }(lines[i], aligns[j], button));
      }
    }

    var refreshImage = function(){
      Contest.previewImage.trigger();
    };

    $("#font").change(refreshImage);
    $("#top,#middle,#bottom").on("input", refreshImage);
  });

// Contest namespace.
var Contest = {};

/**
 *
 * An action, triggered by some user behavior (like keystrokes in a text box),
 * that is delayed my some brief time. Retriggering the delayed action cancels
 * the originally queued action, and restarts the delay timer. This is useful
 * for autocomplete, live search, etc.
 *
 * delayMillis desired delay in milliseconds.
 * action to take when delay expires.
 */
Contest.DelayedAction = function(delayMillis, action) {
  var self = this;
  this.task = function() {
    self.action();
    self.taskId = null;
  };
  this.delayMillis = delayMillis;
  this.action = action;
  this.taskId = null;
};

/**
 * Trigger the (re)start of a delayed action timer.
 */
Contest.DelayedAction.prototype.trigger = function() {
  this.cancel();
  this.taskId = window.setTimeout(this.task, this.delayMillis);
};

/**
 * Cancel a delayed action timer.
 */
Contest.DelayedAction.prototype.cancel = function() {
  if (this.taskId) {
    window.clearTimeout(this.taskId);
  }
  this.taskId = null;
};

/**
 * This delayed action fetches live meme previews while the user types funny
 * text into the meme creation form.
 */
Contest.previewImage = new Contest.DelayedAction(350, function() {
    var previewtext = $('#previewtext'),
    contest_key = $('#contest_key').val(),
    top = $('#top').val(),
    middle = $('#middle').val(),
    bottom = $('#bottom').val(),
    topalign = $('#topalign').val(),
    middlealign = $('#middlealign').val(),
    bottomalign = $('#bottomalign').val();
    if (top.length === 0 && bottom.length === 0 && middle.length === 0) {
      previewtext.hide();
      return;
    }
    previewtext.attr('src',
                     '/previewtext?contest_key=' + encodeURIComponent(contest_key) +
                     '&font=' + encodeURIComponent($('#font').val()) +
                     '&top=' + encodeURIComponent(top) +
                     '&middle=' + encodeURIComponent(middle) +
                     '&bottom=' + encodeURIComponent(bottom) +
                     '&topalign=' + encodeURIComponent(topalign) +
                     '&middlealign=' + encodeURIComponent(middlealign) +
                     '&bottomalign=' + encodeURIComponent(bottomalign)).show();
  });

function formSubmit(){
  var top = $.trim($('#top').val());
  var middle = $.trim($('#middle').val());
  var bottom = $.trim($('#bottom').val());

  if (top == '' && middle == '' && bottom == ''){
    alert('Be funny. Add some text!');
    return false;
  }

  var name = $.trim($('#name').val());
  if (name == ''){
    alert("What's your name?");
    return false;
  }
  return true;
}
